package by.alex.dzeshko.facebooksuperclient.async.common;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import by.alex.dzeshko.facebooksuperclient.R;
import by.alex.dzeshko.facebooksuperclient.http.HttpManager;
import by.alex.dzeshko.facebooksuperclient.http.RequestBuilder;

public abstract class CommonAsyncTask<T> extends
		AsyncTask<by.alex.dzeshko.facebooksuperclient.http.RequestBuilder, java.lang.Void, T> {
	
	private static final String LOG_TAG = "CommonAsyncTask";
	private ParamCallback<T> mParamCallback;
	
	public CommonAsyncTask(ParamCallback<T> paramCallback) {
		super();
		this.mParamCallback = paramCallback;
	}

	protected Exception e; 
	
	@Override
	protected T doInBackground(RequestBuilder... params) {
		try {
			Log.d("string for load", params[0].getUrl());
			Object source = HttpManager.getInstance().loadAsString(params[0].getUrl());
			return convert(source);
		} catch (Exception e) {
			this.e = e;
			Log.e(LOG_TAG, e.toString());
		}
		return null;
	}

	public abstract T convert(Object source) throws Exception;

	@Override
	protected void onPostExecute(T result) {
		super.onPostExecute(result);
		if (e != null) {
			mParamCallback.onError(e);
		} else {
			mParamCallback.onSuccess(result);
		}
	}
	
	public void start(RequestBuilder... params) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
	    } else {
            execute(params);
	    } 
	}

}
